package util.shiro;
import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import dao.user.UserManageDao;
import entities.login.User;
import entities.permission.Permission;
import entities.permission.Role;
import service.user.UserManageService;
/**
 * 
 * shiroRealm 
 * @author hxl
 * 2018年11月22日
 */
@Component("shiroRealm")
public class shiroRealm extends AuthorizingRealm {
	@Resource
    private UserManageDao userManageDao; 
	@Resource
    private UserManageService userManageService; 
    /**
     *权限认证 
     */
	@Override
	@Cacheable(value="shiroCache",key="#principals")
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.fromRealm(getName()).iterator().next();
		User user=userManageService.getUserPermissions(userName);
        if( user != null ) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for( Role role : user.getRoles() ) {
                info.addRole(role.getName());
                Collection<String> permissions= new ArrayList<String>();
                for(Permission permission:role.getPermissions()){
                	permissions.add(permission.getName());
                }
                info.addStringPermissions(permissions);
            }
            return info;
        } else {
        	throw new AuthenticationException();
        }
	}
	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken aucatoken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)aucatoken;
		String name=token.getUsername();
		User user=userManageDao.getUser(null,name);
        if(user!=null){
        	Subject currentUser = SecurityUtils.getSubject(); 
        	Session session=currentUser.getSession();
        	session.setAttribute("currentUser",user);
            return new SimpleAuthenticationInfo(user.getName(),user.getPassword(),getName());  
        }else{
            throw new AuthenticationException();  
        }
	}

}
